import fs from 'fs'
import client from '../client'
import util from '../../utils'
import path from 'path'
import config from '../../config'

class Nova {
  constructor() {}
  async createServer() {
    let url = await util.generateRquestUrl('nova', 'createServer')
    let name = 'xltest-' + Date.now()
    let data = {
      server: {
        name: name,
        imageRef: config.imageRef,
        flavorRef: config.flavorRef,
        networks: [{ uuid: config.networkId }],
        max_count: 1,
        min_count: 1
      }
    }
    let res = await client.post(url, data)
    let location = res.headers.location
    let status = await this.showServer(name, location)
    return { status: status }
  }
  async createServerVolume() {
    let url = await util.generateRquestUrl('nova', 'createServerVolume')
    let name = 'xltest-' + Date.now()
    let data = {
      server: {
        name: name,
        imageRef: '',
        flavorRef: config.flavorRef,
        networks: [{ uuid: config.networkId }],
        max_count: 1,
        min_count: 1,
        block_device_mapping_v2: [
          {
            boot_index: '0',
            uuid: config.imageRef,
            volume_size: '10',
            source_type: 'image',
            destination_type: 'volume',
            delete_on_termination: true
          }
        ]
      }
    }
    let res = await client.post(url, data)
    let location = res.headers.location
    let status = await this.showServer(name, location)
    return { status: status }
  }
  async showServer(name, location, times = 0) {
    let url = await util.generateRquestUrl('nova', 'showServer', name)
    let res = await client.get(location)
    let status = res.server.status
    if (status == 'BUILD' && times < 20) {
      await util.sleep(500)
      return this.showServer(name, location, ++times)
    } else {
      return status
    }
  }
}

export default Nova
